from django.http import HttpResponseServerError, HttpResponse
from django.contrib.auth.decorators import permission_required
from django.core import serializers

from i18ndyn.models import InternationalText, InternationalChar


models = {'InternationalText': InternationalText,
          'InternationalChar': InternationalChar,
          }

def itext_ajax(request):
    """
    This returns the value of the the text for a given language and code.
    """
    if not request.GET.has_key('itext_id') or \
       not request.GET.has_key('itext_lang') or \
       not request.GET.has_key('itext_model'):
        return HttpResponseServerError('Invalid get variables.')

    try:
        model = models[request.GET['itext_model']]
    except:
        return HttpResponseServerError('Invalid get variables.')

    
    try:
        
        itext = model.objects.get(id = request.GET['itext_id'])
    except:
        return HttpResponseServerError('International text object not found.')

    render_text = str(itext.render(request.GET['itext_lang'], False))

    return HttpResponse(render_text)
    
itext_ajax = permission_required('i18ndyn.view_texttranslation')(itext_ajax)
